//
//  TextCodeViewController.m
//  PlayerWorld
//
//  Created by 汪的一声就哭了！ on 16/6/24.
//  Copyright © 2016年 刘成. All rights reserved.
//

#import "TextCodeViewController.h"
#import "UIKit+AFNetworking.h"
#import "PlaceholderTextView.h"
#import "PLFiveObject.h"
#import "ConfirmationViewController.h"
#import "G_P_Object.h"
#import "ILView.h"
@interface TextCodeViewController ()
@property (nonatomic, strong) PlaceholderTextView *textView;
@property (nonatomic, strong) NSTimer *_timer;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *ruleLabel;
@end

@implementation TextCodeViewController
{
    NSString *_headString;
    NSString *_footString;
    NSInteger secondsCountDown;
    NSArray *_array;
    NSMutableArray *_flagArray;
}
-(void)obtainData
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = @"http://666.lefun6.com/";
    
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:@"Game" forKey:@"Model"];
    [parametersDic setObject:@"GetTheIssueAndTime" forKey:@"Action"];
    [parametersDic setObject:self.G_N_Id forKey:@"Id"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 解析成功隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        _model = [[PLFiveObject alloc] init];
        [_model setValuesForKeysWithDictionary:dic];
        secondsCountDown = [_model.overtime integerValue];
        if (secondsCountDown>0) {
            __timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
        }
        else{
            [self obtainData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }];
    
}
// 倒计时方法
-(void)timeFireMethod{
    //倒计时-1
    secondsCountDown--;
    //修改倒计时标签现实内容
    //    labelText.text=[NSString stringWithFormat:@"%d",secondsCountDown];
    NSString *secondValue = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(secondsCountDown/60/60)%60,(secondsCountDown/60)%60,secondsCountDown%60];
    self.timeLabel.text= secondValue;
    //当倒计时到0时，做需要的操作
    if(secondsCountDown==0){
        [self obtainData];
        [__timer invalidate];
    }
}
#pragma mark - 判断字符串是不是数字
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _headString = [[self.G_P_Model.G_P_NumberName componentsSeparatedByString:@"|"] firstObject];
    NSArray *array = [self.G_P_Model.G_P_NumberName componentsSeparatedByString:@"|"];
    _footString = [[self.G_P_Model.G_P_NumberName componentsSeparatedByString:@"|"] objectAtIndex:array.count-2];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, 25)];
    [self.view addSubview:titleLabel];
    titleLabel.text = self.G_P_Model.G_P_Name;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20+25, self.view.bounds.size.width, 20)];
    [self.view addSubview:self.timeLabel];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.view.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:236.0/255.0 blue:237.0/255.0 alpha:1];
    [self obtainData];
    self.textView = [[PlaceholderTextView alloc] initWithFrame:CGRectMake(10, 60+20, self.view.bounds.size.width-20, 90)];
    self.textView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.textView];
    self.textView.placeholder = @"请在下方的输入框输入或粘帖投注内容，每注请使用空格分隔开";
    self.textView.layer.borderWidth = 1;
    self.textView.layer.cornerRadius = 8;
    self.textView.layer.borderColor = [UIColor grayColor].CGColor;
    
    self.ruleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 160+20, self.view.bounds.size.width-20, 200)];
    self.ruleLabel.numberOfLines = 0;
    self.ruleLabel.textColor = [UIColor lightGrayColor];
    self.ruleLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.ruleLabel];
    self.ruleLabel.text = self.G_P_Model.G_P_Text;
    [self.ruleLabel sizeToFit];
    _array = @[@"万",@"千",@"百",@"十",@"个"];
    _flagArray = [NSMutableArray array];
    for (NSInteger i = 0; i < 5; i++) {
        ILView *view = [[ILView alloc] initWithFrame:CGRectMake(i*(self.view.bounds.size.width/5), 20+45, self.view.bounds.size.width/5, 12)];
        view.label.font = [UIFont systemFontOfSize:12];
        view.label.text = [NSString stringWithFormat:@"%@位",_array[i]];
        view.tag = 1000+i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(choosePlaceAction:)];
        [view addGestureRecognizer:tap];
        if ([self isPureInt:_headString]) {
            [self.view addSubview:view];
        }
        [_flagArray addObject:[NSNumber numberWithBool:NO]];
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确认" style:UIBarButtonItemStylePlain target:self action:@selector(sureBtnAction:)];
}
- (void)choosePlaceAction:(UITapGestureRecognizer *)tap
{
    ILView *view = (ILView *)tap.view;
    NSInteger integer = view.tag - 1000;
    if ([view.imageView.image isEqual:[UIImage imageNamed:@"quan"]]) {
        view.imageView.image = [UIImage imageNamed:@"quan1"];
        [_flagArray setObject:[NSNumber numberWithBool:YES] atIndexedSubscript:integer];
    }
    else{
        view.imageView.image = [UIImage imageNamed:@"quan"];
        [_flagArray setObject:[NSNumber numberWithBool:NO] atIndexedSubscript:integer];
    }
}
- (void)sureBtnAction:(UIButton *)btn
{
    NSMutableString *muString = [NSMutableString string];
    if ([self isPureInt:_headString]) {
        NSInteger yNum = 0;
        for (NSString *string in _array) {
            NSInteger inte = [_array indexOfObject:string];
            if ([_flagArray[inte] boolValue]) {
                [muString appendString:string];
                yNum++;
            }
        }
        if (yNum != [_headString integerValue]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"输入不正确" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }
        [muString appendString:@":"];
    }
    NSInteger num;
    if ([self isPureInt:_headString]) {
        num = [_headString integerValue];
    }
    else{
        num = _headString.length;
    }
    NSString *textStr = [[[self.textView.text componentsSeparatedByString:@"---------"] firstObject] stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    textStr = [textStr stringByReplacingOccurrencesOfString:@"\r" withString:@" "];
    NSArray *array = [textStr componentsSeparatedByString:@" "];
    NSMutableArray *muarr = [NSMutableArray arrayWithArray:array];
    [muarr removeObject:@""];
    NSMutableArray *mutableArr = [NSMutableArray array];
    for (NSString *string in muarr) {
        if ([_footString integerValue] > num) {
            for (NSInteger i = 0 ; i < string.length; i = [_footString integerValue]/num+i) {
                if (![[string substringWithRange:NSMakeRange(i, 1)] isEqualToString:@"0"]) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"输入不正确" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    
                    [alert addAction:action];
                    [self presentViewController:alert animated:YES completion:nil];
                    return;
                }
            }
        }
        if (string.length != [_footString integerValue] || ![self isPureInt:string]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"输入不正确" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
            NSLog(@"%@,%@",string,[string substringWithRange:NSMakeRange(2, 1)]);
            return;
        }
        NSMutableString *lineStr = [NSMutableString stringWithString:string];
        for (NSInteger i = [_footString integerValue]/num; i < (1+[_footString integerValue]/num)*num-1; i = i + (1+[_footString integerValue]/num)) {
            [lineStr insertString:@"|" atIndex:i];
        }
        NSLog(@"%@",lineStr);
        [mutableArr addObject:lineStr];
    }
    NSString *str = [mutableArr componentsJoinedByString:@"$"];
    [muString appendString:str];
    ConfirmationViewController *cVC= [[ConfirmationViewController alloc] init];
    cVC.G_N_Id = _G_N_Id;
    cVC.G_P_Model = _G_P_Model;
    cVC.Issue = _model.Then_Issue;
    cVC.money = mutableArr.count;
    cVC.string = muString;
    [self.navigationController pushViewController:cVC animated:YES];
}
#pragma mark --过滤掉---------文字
-(NSString *)filterText:(NSString *)textStr
{
    NSScanner * scanner = [NSScanner scannerWithString:textStr];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"-" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@"-" intoString:&text];
        //替换字符
        textStr = [textStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@-",text] withString:@""];
        NSLog(@"%@",text);
    }
    return textStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
